<?php
class Product_Service_Putaway
{
	//上架状态
	public static $putaway_status = array(
		"-1" => "草稿",
		"0" => "未确认",
		"1" => "已确认",
		"2" => "已删除",
	);
	
	public function __construct(){
		
	}
	public static function create($row)
	{ 
		$obj=new Product_Model_Putaway();
		return $obj->create($row);
	}

	public static function update($row,$t_id)
	{ 
		$obj=new Product_Model_Putaway();
		return $obj->update($row,$t_id);
	}
	
	public static function updatePutawayCodeAndLot($row,$option)
	{ 
		if($option['putaway_code']=='' || $option['putaway_lot_number']==''){
			return;
		}
		$obj=new Product_Model_Putaway();
		return $obj->updatePutawayCodeAndLot($row,$option);
	}
	
	/**
	 * 获取当天最后一个 putaway_code
	 */
	public static function getCurdateLastCode()
	{ 
		$obj=new Product_Model_Putaway();
		$lastCode=$obj->getCurdateLastCode();
		$PUNO = 'P'.date('ymd');
		$tmp ='';
		if($lastCode){
			$tmp= (int) substr($lastCode,-3,3);
			$tmp= str_pad(($tmp+1),3,'0',STR_PAD_LEFT);
		}else{
			$tmp ='001';
		}
		$PUNO.=$tmp;
		return $PUNO;
	}
	
	public static function getByReceivingCode($code)
	{ 
		$obj=new Product_Model_Putaway();
		$rows=$obj->getByReceivingCode($code);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}
	
	public static function getByPutawayId($id)
	{ 
		$obj=new Product_Model_Putaway();
		$rows=$obj->getByPutawayId($id);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}

	public static function getByPutawayAndLot($condition)
	{ 
		$obj=new Product_Model_Putaway();
		$rows=$obj->getByPutawayAndLot($condition);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}
	
	/**
	*根据product_id、receiving_code获取产品上架数量
	*return array('putaway_total'=>上架总数,'verify_putaway_total'=>已确认上架的总数)
	*/
	public static function getByPutawayTotal($option)
	{ 
		$tmpTotal=0;		//上架总数
		$verifyTotal=0;			//已完成上架总数
		$contion=array(
			'product_id'=>$option['product_id'],
			'receiving_code'=>$option['receiving_code'],
		);
		$rows=self::getByCondition($contion,"*");
		$result=array();
		foreach($rows as $k => $v){
			if($v['putaway_status']=='1'){
				$verifyTotal+=$v['putaway_quantity'];
			}
			$tmpTotal+=$v['putaway_quantity'];
		}
		$result['putaway_total']=$tmpTotal;
		$result['verify_putaway_total']=$verifyTotal;
		return $result;
	}
	
	public static function getByCondition($condition=array(),$type='*',$page="0", $pageSize="0")
	{ 
		if(isset($condition["putaway_date_from"]) && $condition['putaway_date_from'] != ""){
			$condition['putaway_date_from']=date('Y-m-d',strtotime("{$condition['putaway_date_from']}"))." 00:00:00"; 
		}
		if(isset($condition["putaway_date_to"]) && $condition['putaway_date_to'] != ""){
			$condition['putaway_date_to']=date('Y-m-d',strtotime("{$condition['putaway_date_to']}"))." 23:59:59"; 
		}
		$obj=new Product_Model_Putaway();
		$rows= $obj->getByCondition($condition,$type, $page,$pageSize);	
		return $rows;
	}

	/**
	*验证提交的数据
	*@data=array() @type 0=创建上架 1=确认上架
	*/
	public static function validate($data=array(),$type=0)
	{
		$quantity=$data['quantity']; //数量
		$ws_code=$data['ws_code']; //货架号
		$putaway_lot_number=$data['putaway_lot_number']; //批次号
		$product_id=$data['product_id']; //产品ID
		$product_sku=$data['product_sku']; //产品SKU
		$putaway_id=@$data['putaway_id'];  //上架ID confirm确认上架时才用到
		$receiving_code=@$data['receiving_code']; //string 上架时用到
		
		if(isset($data['putaway_ids'])){
			$putaway_ids=$data['putaway_ids']; //有可能来自QC草稿
		}
		$error=array();
		//验证上架数量
		foreach($quantity as $key => $val){
			if($val<1||$val==''){$error[]="LotID: ".$putaway_lot_number[$key]." ,上架数量不能小于或等于0";} //不允许数量为0
		}
		//验证货架号
		
		$product_ws_code=array();
		foreach($ws_code as $key => $val){
			$error_ws_code=false;
			if($val==''){
				$error[]="LotID: ".($putaway_lot_number[$key])." ,货架号不能为空!";
			}else{
				$condition=array(
					'ws_code'=>$val,
					'product_id'=>$product_id[$key],
				);
				$wssRow=Warehouse_Service_Shelf::getByfield('ws_code',$val);
				$wspRow=Warehouse_Service_Products::getByCondition(array('ws_code'=>$val,'wp_status'=>'1'));
				if(!empty($wspRow)){
					if($wspRow['product_id']!=$product_id[$key]){
						$error_ws_code=true;
					}
				}
				if(empty($wssRow)){
					$error[]="货架号:".$val."不存在!";
				}elseif($wssRow['ws_statu']!=1){
					$error[]="货架号:".$val."不可用!";
				}elseif($error_ws_code){
					$error[]="货架号:".$val."已经存放其它的产品! ".$wspRow['product_id'].'  >>  '.$product_id[$key];
				}elseif(!Warehouse_Service_Shelf::getByJoinChooseCondition($condition,"count(*)")){
					$error[]="货架号:".$val."与产品目录不符!";
				}else{
					$option=array(
						'putaway_status'=>'0',
						'ws_code'=>$val,
					);
					$pRows=self::getByCondition($option,"*",'',0,0);
					if(!empty($pRows)){
						if($pRows[0]['product_id'] != $product_id[$key]){
							$error[]="货架号:".$val." 已被 ".$pRows[0]['putaway_code']." 批次 ".$pRows[0]['putaway_lot_number']." 占用!";
						}
					}
				}
			}
			$product_ws_code[$product_id[$key]][]=$val;
		}
		
		//验证多个产品使用同一个货架号
		$type_ws_code=array();
		foreach($product_ws_code as $key => $value){
			$type_ws_code[$key]=array();
			foreach($product_ws_code[$key] as $k => $v){
				if(!in_array($v,$type_ws_code[$key])){
					$type_ws_code[$key][]=$v;
				}
			}
		}
		//合并各产品货架号
		$all_type_ws_code=array();
		foreach($type_ws_code as $key => $value){
			foreach($value as $k => $v){
				$all_type_ws_code[]=$v;
			}
		}
		//查找重复的货架号
		$array_count=array_count_values($all_type_ws_code);
		foreach($array_count as $key => $value){
			if($value>1){
				$error[]="货架号:".$key." 不可以多个产品共用一个货架号!";
			}
		}
		
		if($type==0){//用于验证创建上架时
			if($receiving_code==''){
				return $error=array("receiving_code,不能为空!");
			}
			//验证产品个数/提交数量
			$product_total=array();		//提交总数
			$productIds=array(); 		//产品ID
			$productSKU=array();		//产品SKU
			foreach($product_id as $key => $val){
				if(!in_array($val,$productIds)){
					$productIds[]=$val;
					$product_total[$val]=0;
					$productSKU[$val]=$product_sku[$key];
				}
				if(in_array($val,$productIds)){
					$product_total[$val]+=$quantity[$key];
				}
			}
			//数量不能大于等待上架数量
			foreach($productIds as $key => $val){
				$cond=array(
					'product_id'=>$val,
					'receiving_code'=>$receiving_code,
				);
				$PSRrows=Product_Service_ReceivingItem::getByReceivingAsnPid($cond);
				$wait_total=$PSRrows['received_qty']-$PSRrows['putaway_qty'];//等上架总数量
				if($product_total[$val]>$wait_total){
					$error[]="产品SKU:".$productSKU[$val].",上架数量(".$product_total[$val].")大于待上架总数量(".$wait_total.")!";
				}
			}
		}else{//用于验证确认上架
			if(empty($putaway_id)){
				return $error=array("putaway_id,不能为空!");
			}
			//验证产品个数/提交数量/重复提交
			$putaway_total=array();		//提交总数
			$putawayIds=array(); 		//上架ID
			$putawayproductSKU=array();		//产品SKU
			foreach($putaway_id as $key => $val){
				$psprows=Product_Service_Putaway::getByPutawayId($val);
				if($psprows['putaway_status']=='1'){
					$error[]="LotID: ".$psprows['putaway_lot_number']." 已完成上架,请勿重复提交!";
				}
				if(!in_array($val,$putawayIds)){
					$putawayIds[]=$val;
					$putaway_total[$val]=0;
					$putawayproductSKU[$val]=$product_sku[$key];
				}
				if(in_array($val,$putawayIds)){
					$putaway_total[$val]+=$quantity[$key];
				}
			}
			//修改后的数量不能大于当前上架数量
			foreach($putawayIds as $key => $val){
				$psprows=Product_Service_Putaway::getByPutawayId($val);
				if($putaway_total[$val]>$psprows['putaway_quantity']){
					$error[]="产品SKU:".$putawayproductSKU[$val].",修改后的上架数量(".$putaway_total[$val]."),不能大于上架总数量(".$psprows['putaway_quantity'].")!";
				}
			}
		}
		return $error;
	}
	
	/**
	*创建上架单
	*@return 0:失败;返回putaway_code:成功;
	*/
	public static function proccreatePutawayTransaction($options=array()){
	
		$quantity=$options['quantity'];
		$ws_code=$options['ws_code'];
		$putaway_lot_number=$options['putaway_lot_number'];
		$product_id=$options['product_id'];
		if(isset($options['putaway_ids'])){
			$param_putaway_ids=$options['putaway_ids']; //有可能来自QC草稿
			$putaway_ids=array();
			foreach($param_putaway_ids as $key => $val){
				if(!in_array($val,$putaway_ids)){
					$putaway_ids[]=$val;
				}
			}
		}
		
		//以上都是数组类型
		$receiving_code=$options['receiving_code'];
		$warehouse_id=@$options['warehouse_id'];
		$warehouse_id=($warehouse_id!='')?$warehouse_id:1;
		$putaway_note=@$options['putaway_note'];
		$putaway_note=($putaway_note!='')?$putaway_note:'create';
		
		$date=date("Y-m-d:H:i:s");
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;					//操作人
		$WMProducts = new Warehouse_Model_Products();
		$dbAdapter = $WMProducts->getAdapter();
		$dbAdapter->beginTransaction(); 
		try{
			//删除提交时的草稿putaway_code
			if(isset($putaway_ids) && is_array($putaway_ids) ){
				$putawayModel = new Product_Model_Putaway();
				foreach($putaway_ids as $val){
					if(!$putawayModel->delete($val)){
						$dbAdapter->rollback();
						return false;
					}
				}
			}
			
			$putaway_code=Product_Service_Putaway::getCurdateLastCode();//查找当天最后一个
			
			foreach($product_id as $key => $val){
				$putawayRow=array(
					'receiving_code'=>$receiving_code,
					'putaway_code'=>$putaway_code,
					'product_id'=>$val,
					'putaway_create_date'=>$date,
					'warehouse_id'=>$warehouse_id,
					'create_user_id'=>$user_id,
					'putaway_note'=>$putaway_note,
					'putaway_status'=>0,//等待确认
					'putaway_quantity'=>$quantity[$key],	//上架数量
					'putaway_lot_number'=>$putaway_lot_number[$key],			//上架批次号
					'ws_code'=>strtoupper($ws_code[$key]),					//货架号
				);
				if(Product_Service_Putaway::create($putawayRow)){
					$cond=array(
						'product_id'=>$val,
						'receiving_code'=>$receiving_code,
					);
					$PSRrows=Product_Service_ReceivingItem::getByReceivingAsnPid($cond);
					$updateRow=array(
						'putaway_qty'=>$PSRrows['putaway_qty']+$quantity[$key],
					);
					$where=array(
						'product_id'=>$val,
						'receiving_code'=>$receiving_code,
					);
					if(!Product_Service_ReceivingItem::updateAsnPid($updateRow,$where)){
						$dbAdapter->rollback();
						return false;
					}
				}else{
					$dbAdapter->rollback();
					return false;
				}
			}
			$dbAdapter->commit();
			return $putaway_code;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return false;
		}
	}
	
	/**
	*确认产品上架
	*@return 0:失败;1:成功;
	*/
	public static function procPutawayTransaction($options=array()){
		$putaway=array(
			'receiving_code'=>$options['receiving_code'], 	//string
			'putaway_code'=>$options['putaway_code'],		//string
			'warehouse_id'=>1,
			'putaway_note'=>'create',
			'putaway_status'=>1,			//状态已完成
			'product_id'=>$options['product_id'],					//产品ID   array
			'putaway_quantity'=>$options['quantity'],				//上架数量 array
			'ws_code'=>$options['ws_code'],							//货架号   array
			'putaway_lot_number'=>$options['putaway_lot_number'],	//批次号   array
		);
		if($putaway['receiving_code']=='' || $putaway['putaway_code']==''){
			return false;
		}
		$date=date("Y-m-d:H:i:s");
		$WMProducts = new Warehouse_Model_Products();
		$dbAdapter = $WMProducts->getAdapter();
		$dbAdapter->beginTransaction(); 
		try{
			//验证产品个数/提交数量
			$product_total=array();		//提交总数
			$productIds=array(); 		//产品ID
			foreach($putaway['product_id'] as $key => $val){
				$putawayRow=array(
					'receiving_code'=>$putaway['receiving_code'],
					'putaway_code'=>$putaway['putaway_code'],				//上架清单号不改变
					'putaway_date'=>$date,
					'putaway_create_date'=>$date,
					'warehouse_id'=>$putaway['warehouse_id'],
					'putaway_note'=>$putaway['putaway_note'],
					'product_id'=>$val,
					'putaway_status'=>$putaway['putaway_status'],						//1.已完成
					'putaway_quantity'=>$putaway['putaway_quantity'][$key],				//上架数量
					'putaway_lot_number'=>$putaway['putaway_lot_number'][$key],			//上架批次号
					'ws_code'=>strtoupper($putaway['ws_code'][$key]),					//货架号
				);
				if(!Product_Service_Putaway::procPutaway($putawayRow)){
					$dbAdapter->rollback();
					return false;
				}
				
				//统计各产品提交数量
				if(!in_array($val,$productIds)){
					$productIds[]=$val;
					$product_total[$val]=0;
				}
				if(in_array($val,$productIds)){
					$product_total[$val]+=$putaway['putaway_quantity'][$key];
				}
			}
			//更新产品库存/写入日志
			foreach($product_total as $key =>$val){
				if(!Product_Service_ProductStocket::updateQuantity($key,$val)){
					$dbAdapter->rollback();
					return false;
				}
			}
            $dbAdapter->commit();
            return array('ask' => '1', 'putaway_code' => $putaway['putaway_code']);
        } catch (Exception $e) {
            $dbAdapter->rollback();
            return array('ask' => '0', 'error' => $e->getMessage());
        }
	}
	private function procPutaway($options){
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;					//操作人
		$date=date("Y-m-d:H:i:s");
		$putawayRow=array(
			'putaway_code'=>$options['putaway_code'],
			'receiving_code'=>$options['receiving_code'],
			'product_id'=>$options['product_id'],
			'putaway_date'=>$date,
			'putaway_create_date'=>$date,
			'create_user_id'=>$user_id,
			'putaway_user_id'=>$user_id,
			'putaway_status'=>$options['putaway_status'],//已完成
			'warehouse_id'=>$options['warehouse_id'],
			'putaway_note'=>$options['putaway_note'],
			'putaway_quantity'=>$options['putaway_quantity'],				//上架数量
			'putaway_lot_number'=>$options['putaway_lot_number'],			//上架批次号
			'ws_code'=>strtoupper($options['ws_code']),						//货架号
		);
		//判断如果批次号已存在，则修改，反之添加
		$condition=array(
			'receiving_code'=>$putawayRow['receiving_code'],
			'putaway_code'=>$putawayRow['putaway_code'],
			'putaway_lot_number'=>$putawayRow['putaway_lot_number'],
			'warehouse_id'=>$putawayRow['warehouse_id'],
		);
		if(self::getByCondition($condition,'count(*)')>0){
			$updateRow=array(
				'putaway_date'=>$date,
				'putaway_note'=>'edit',
				'putaway_user_id'=>$user_id,
				'putaway_status'=>1,//confirm 状态已完成
				'ws_code'=>strtoupper($putawayRow['ws_code']),
				'putaway_quantity'=>$putawayRow['putaway_quantity'],	//上架数量
			);
			$where=array(
				'putaway_code'=>$putawayRow['putaway_code'],
				'putaway_lot_number'=>$putawayRow['putaway_lot_number'],
			);
			if(!self::updatePutawayCodeAndLot($updateRow,$where)){
                throw new Exception('更新上架状态失败!');
				return false;
			}
		}else{
			if(!self::create($putawayRow)){
                throw new Exception('创建上架批次失败!批次:'.$putawayRow['putaway_lot_number']);
				return false;
			}
		}
		$current_quantity=0;//当前库存数量
        $quantity=0;
        //货架使用日志
        $WarehouseProductsLog=array(
            'wpl_refId'=>$putawayRow['putaway_code'],
            'user_id' => $user_id,
            'warehouse_id'=>$putawayRow['warehouse_id'],
            'ws_code' => $putawayRow['ws_code'],
            'wpl_proc_type' => 1, //增加库存
            'wpl_add_time' => $date,
            'wpl_ip' => Warehouse_Service_Shelf::getIP(),
            'wpl_note'=>'putaway',
        );
        $condition = array(
            'ws_code' => $putawayRow['ws_code'],
            'warehouse_id'=>$putawayRow['warehouse_id'],
        );
		$wspRows=Warehouse_Service_Products::getByCondition($condition);
        //查看货架是否已占用
		if(!empty($wspRows)){
            $wmpRowobj = new Warehouse_Model_Products();
            $wspRow = $wmpRowobj->lockForUpdate($condition); //lockFor

            //状态不可用才更新为可用，避免还有其它状态
            if ($wspRows['wp_status'] == '0') {
                $quantityupdateRow['wp_status'] = 1;
                $quantityupdateRow['wp_quantity'] = $putawayRow['putaway_quantity'];
                $quantity = $putawayRow['putaway_quantity'];
                $quantityupdateRow['wp_quantity_hold'] = 0;
                $quantityupdateRow['product_id'] = $putawayRow['product_id'];

                $WarehouseProductsLog['wpl_proc_type'] = 3; //内容修改
                $note='产品上架,状态由:0 修改为:1; 数量:' .$quantityupdateRow['wp_quantity'];
                if ($wspRows['product_id'] == $putawayRow['product_id']) {
                    $WarehouseProductsLog['wpl_note'] =$note;
                }else{
                    $WarehouseProductsLog['wpl_note'] =$note.' 产品ID由: '.$wspRows['product_id'] .'修改为: '.$putawayRow['product_id'];
                }

            } elseif ($wspRows['wp_status'] == '1' && $wspRows['product_id'] == $putawayRow['product_id']) {
                $quantity = $wspRow['wp_quantity'] + $putawayRow['putaway_quantity'];
                $quantityupdateRow['wp_quantity'] = $quantity;

                $WarehouseProductsLog['wpl_proc_type'] = 1; //增加库存
                $WarehouseProductsLog['wpl_note'] ='产品上架,数量由' .$wspRow['wp_quantity'].'修改为:'.$quantity;

            } else {
                //其它的状态情况不允许上架
                throw new Exception('货架号:' . $putawayRow['ws_code'] . '状态('.$wspRows['wp_status'].')异常,上架失败!'.$wspRows['product_id'] .'=>'. $putawayRow['product_id']);
                return false;
            }

            $current_quantity = $quantity;
            //修改库存
            $quantityupdateRow['wh_last_update']=$date;
            if ($wmpRowobj->update($quantityupdateRow, $wspRow['wp_id'])) {
                //写入货架使用日志
                if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
                    throw new Exception('写入货架使用日志失败!wpl');
                    return false;
                }
            } else {
                throw new Exception('更新货架库存错误!');
                return false;
            }

		}else{
			$PSProw=Product_Service_Product::getByProductId($putawayRow['product_id']);
			$addRow=array(
				'warehouse_id'=>1,
				'customer_id'=>$PSProw['customer_id'],
				'ws_code'=>$putawayRow['ws_code'],
				'product_id'=>$putawayRow['product_id'],
				'wp_quantity'=>$putawayRow['putaway_quantity'],
				'wh_create_date'=>$date,
				'wh_last_update'=>$date,
			);
			//添加库存产品
			if(!Warehouse_Service_Products::add($addRow)){
                throw new Exception('创建货架库存错误!');
				return false;
			}
		}
		$qco_code='';
		$QcOrder = Product_Service_QualityControlOrder::getByQcoRefCode($putawayRow['receiving_code']);
		if(!empty($QcOrder)){
			$qco_code=$QcOrder['qco_code'];
		}
		//add 产品上架批次表
		$addWPB=array(
			'ws_code'=>$putawayRow['ws_code'],
			'putaway_code'=>$putawayRow['putaway_code'],
			'receiving_code'=>$putawayRow['receiving_code'],
			'putaway_lot_number'=>$putawayRow['putaway_lot_number'],
			'wpb_quantity'=>$putawayRow['putaway_quantity'],
			'product_id'=>$putawayRow['product_id'],
			'wpb_status'=>1,
			'qco_code'=>$qco_code,
			'wpb_create_time'=>$date,
			'wpb_last_update'=>$date
		);
		$insertid=Warehouse_Service_ProductsBatch::create($addWPB);
		if($insertid<1){
            throw new Exception('创建产品上架批次错误!');
			return false;
		}
		//写入使用日志
		$addWSP=array(
			'wpu_type'=>1,
			'wpu_proc_type'=>1,
			'wpu_refId'=>$putawayRow['putaway_code'],
			'wpu_quantity'=>$putawayRow['putaway_quantity'],
			'wpu_current_qty'=>$current_quantity,
			'wpu_note'=>'产品上架',
			'wpb_id'=>$insertid,
			'wpu_create_time'=>$date,
		);
		if(!Warehouse_Service_ProductUseage::create($addWSP)){
            throw new Exception('写入上架批次日志错误!');
			return false;
		}

		return true;
	}
	
	
}